<template>
  <div class="home">
    <section class="hero">
      <h1>欢迎来到 Xuejun Airline </h1>
      <p>为您提供舒适、安全、便捷的航空服务</p>
    </section>

    <!-- 推荐图片模块 -->
    <section class="recommend-section">
      <div class="section-header">
        <h2>精彩推荐</h2>
        <button @click="showUploadDialog = true" class="upload-button">
          📷 上传图片
        </button>
      </div>
      <div class="image-grid">
        <div
          v-for="image in recommendImages"
          :key="image.id"
          class="image-card"
        >
          <img :src="getImageUrl(image.url)" :alt="image.title" />
          <div class="image-title">{{ image.title }}</div>
        </div>
      </div>
    </section>

    <!-- 图片上传对话框 -->
    <div v-if="showUploadDialog" class="upload-dialog-overlay" @click="closeUploadDialog">
      <div class="upload-dialog" @click.stop>
        <div class="dialog-header">
          <h3>上传推荐图片</h3>
          <button @click="closeUploadDialog" class="close-button">&times;</button>
        </div>

        <div class="upload-content">
          <div class="upload-area"
               :class="{ 'dragover': isDragOver }"
               @dragover.prevent="isDragOver = true"
               @dragleave.prevent="isDragOver = false"
               @drop.prevent="handleFileDrop">

            <input
              ref="fileInput"
              type="file"
              accept="image/*"
              @change="handleFileSelect"
              style="display: none"
            />

            <div v-if="!selectedFile" class="upload-placeholder">
              <div class="upload-icon">📷</div>
              <p>拖拽图片到这里或点击选择</p>
              <button @click="$refs.fileInput.click()" class="select-file-button">
                选择文件
              </button>
              <p class="upload-tips">支持 JPG、PNG、GIF 格式，最大 5MB</p>
            </div>

            <div v-else class="file-preview">
              <img :src="previewUrl" alt="预览" class="preview-image" />
              <div class="file-info">
                <p class="file-name">{{ selectedFile.name }}</p>
                <p class="file-size">{{ formatFileSize(selectedFile.size) }}</p>
                <button @click="removeSelectedFile" class="remove-file-button">
                  移除文件
                </button>
              </div>
            </div>

            <!-- 图片信息输入区域 -->
            <div v-if="selectedFile" class="image-info-inputs">
              <div class="input-group">
                <label for="image-title">图片标题</label>
                <input
                  id="image-title"
                  v-model="imageTitle"
                  type="text"
                  placeholder="请输入图片标题"
                  maxlength="50"
                />
              </div>

              <div class="input-group">
                <label for="image-weight">显示权重</label>
                <div class="weight-input-group">
                  <input
                    id="image-weight"
                    v-model.number="imageWeight"
                    type="number"
                    min="0"
                    max="100"
                    placeholder="0-100"
                  />
                  <span class="weight-description">数字越大，优先级越高</span>
                </div>
              </div>
            </div>
          </div>

          <div class="upload-actions">
            <button @click="closeUploadDialog" class="cancel-button">
              取消
            </button>
            <button
              @click="uploadImage"
              :disabled="!selectedFile || isUploading"
              class="upload-confirm-button"
            >
              {{ isUploading ? '上传中...' : '确认上传' }}
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 机票预定模块 -->
    <section class="flight-search-section">
      <FlightSearch
        title="机票查询"
        :auto-search="true"
        @search="handleSearch"
        @loading-change="handleLoadingChange"
      />

      <FlightSearchResult
        v-if="searchResults.length > 0"
        :flights="searchResults"
        title="搜索结果"
        :loading="searchLoading"
        :show-details="false"
        @book-flight="handleBookFlight"
      />
    </section>
  </div>
</template>

<script>
import api from '../api'
import FlightSearchResult from '../components/FlightSearchResult.vue'
import FlightSearch from '../components/FlightSearch.vue'

export default {
  name: 'HomeView',
  components: {
    FlightSearchResult,
    FlightSearch
  },
  data() {
    return {
      recommendImages: [],
      searchResults: [],
      searchLoading: false,
      // 上传相关数据
      showUploadDialog: false,
      selectedFile: null,
      previewUrl: null,
      isDragOver: false,
      isUploading: false,
      imageTitle: '',
      imageWeight: 0
    }
  },
  async mounted() {
    await this.loadRecommendImages()
  },
  methods: {
    async loadRecommendImages() {
      try {
        const response = await api.get('/recommend/images')
        this.recommendImages = response.data
      } catch (error) {
        console.error('获取推荐图片失败:', error)
      }
    },
    handleSearch(searchData) {
      this.searchResults = searchData.results
    },

    handleLoadingChange(loading) {
      this.searchLoading = loading
    },
    formatDateTime(dateTimeString) {
      if (!dateTimeString) return ''
      const date = new Date(dateTimeString)
      return date.toLocaleString('zh-CN')
    },

    // 上传相关方法
    closeUploadDialog() {
      this.showUploadDialog = false
      this.resetUploadData()
    },

    resetUploadData() {
      this.selectedFile = null
      this.previewUrl = null
      this.isDragOver = false
      this.isUploading = false
      this.imageTitle = ''
      this.imageWeight = 0
    },

    handleFileSelect(event) {
      const file = event.target.files[0]
      if (file) {
        this.processFile(file)
      }
    },

    handleFileDrop(event) {
      this.isDragOver = false
      const file = event.dataTransfer.files[0]
      if (file) {
        this.processFile(file)
      }
    },

    processFile(file) {
      // 检查文件类型
      if (!file.type.startsWith('image/')) {
        alert('请选择图片文件')
        return
      }

      // 检查文件大小 (5MB)
      const maxSize = 5 * 1024 * 1024
      if (file.size > maxSize) {
        alert('文件大小不能超过5MB')
        return
      }

      this.selectedFile = file
      this.previewUrl = URL.createObjectURL(file)
    },

    removeSelectedFile() {
      if (this.previewUrl) {
        URL.revokeObjectURL(this.previewUrl)
      }
      this.resetUploadData()
    },

    async uploadImage() {
      if (!this.selectedFile) return

      // 验证标题
      if (!this.imageTitle.trim()) {
        alert('请输入图片标题')
        return
      }

      // 验证权重
      if (this.imageWeight < 0 || this.imageWeight > 100) {
        alert('权重值必须在0-100之间')
        return
      }

      this.isUploading = true
      try {
        const formData = new FormData()
        formData.append('file', this.selectedFile)
        formData.append('title', this.imageTitle.trim())
        formData.append('weight', this.imageWeight)

        const response = await api.post('/recommend/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })

        // 上传成功
        this.closeUploadDialog()
        await this.loadRecommendImages() // 重新加载图片列表
        alert(`图片"${this.imageTitle}"上传成功！`)

      } catch (error) {
        console.error('上传失败:', error)
        alert('上传失败: ' + (error.response?.data?.message || error.message))
      } finally {
        this.isUploading = false
      }
    },

    formatFileSize(bytes) {
      if (bytes === 0) return '0 Bytes'
      const k = 1024
      const sizes = ['Bytes', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    },

    getImageUrl(url) {
      // 如果URL已经是完整的HTTP URL，直接返回
      if (url.startsWith('http://') || url.startsWith('https://')) {
        return url;
      }
      // 否则拼接后端服务器地址
      return 'http://localhost:8080' + url;
    },

    handleBookFlight(flight) {
      alert(`预订航班 ${flight.flightNumber} - ${flight.departureCity} → ${flight.arrivalCity}`)
    }
  }
}
</script>

<style scoped>
.home {
  max-width: 1200px;
  margin: 0 auto;
}

.hero {
  text-align: center;
  padding: 3rem 0;
  background: linear-gradient(135deg, #003366, #0066cc);
  color: white;
  margin-bottom: 2rem;
  border-radius: 8px;
}

.hero h1 {
  font-size: 2.5rem;
  margin-bottom: 1rem;
}

.hero p {
  font-size: 1.2rem;
}

.recommend-section {
  margin-bottom: 3rem;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 1.5rem;
}

.recommend-section h2 {
  font-size: 1.8rem;
  color: #333;
  margin: 0;
}

.upload-button {
  padding: 0.5rem 1rem;
  background-color: #003366;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.9rem;
  transition: background-color 0.3s;
}

.upload-button:hover {
  background-color: #0055a5;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 1.5rem;
}

.image-card {
  overflow: hidden;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0,0,0,0.1);
}

.image-card img {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.image-title {
  padding: 0.5rem;
  text-align: center;
  font-weight: 500;
}

.flight-search-section {
  margin-bottom: 3rem;
}


/* 上传对话框样式 */
.upload-dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.upload-dialog {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
}

.dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem;
  border-bottom: 1px solid #eee;
}

.dialog-header h3 {
  margin: 0;
  color: #333;
}

.close-button {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  color: #666;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-button:hover {
  color: #333;
}

.upload-content {
  padding: 1.5rem;
}

.upload-area {
  border: 2px dashed #ddd;
  border-radius: 8px;
  padding: 2rem;
  text-align: center;
  transition: border-color 0.3s;
  margin-bottom: 1.5rem;
}

.upload-area.dragover {
  border-color: #003366;
  background-color: #f0f7ff;
}

.upload-placeholder {
  color: #666;
}

.upload-icon {
  font-size: 3rem;
  margin-bottom: 1rem;
}

.upload-placeholder p {
  margin: 0.5rem 0;
}

.select-file-button {
  padding: 0.5rem 1rem;
  background-color: #003366;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  margin-top: 1rem;
}

.select-file-button:hover {
  background-color: #0055a5;
}

.upload-tips {
  font-size: 0.8rem;
  color: #999;
  margin-top: 1rem;
}

.file-preview {
  display: flex;
  gap: 1rem;
  align-items: center;
}

.preview-image {
  width: 100px;
  height: 100px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #ddd;
}

.file-info {
  flex: 1;
  text-align: left;
}

.file-name {
  font-weight: 500;
  margin: 0;
  color: #333;
}

.file-size {
  color: #666;
  margin: 0.25rem 0;
}

.remove-file-button {
  padding: 0.25rem 0.5rem;
  background-color: #e74c3c;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 0.8rem;
  margin-top: 0.5rem;
}

.remove-file-button:hover {
  background-color: #c0392b;
}

.upload-actions {
  display: flex;
  justify-content: flex-end;
  gap: 1rem;
  margin-top: 1.5rem;
}

.cancel-button {
  padding: 0.5rem 1rem;
  background-color: #6c757d;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-button:hover {
  background-color: #5a6268;
}

.upload-confirm-button {
  padding: 0.5rem 1rem;
  background-color: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.upload-confirm-button:hover:not(:disabled) {
  background-color: #218838;
}

.upload-confirm-button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

/* 图片信息输入样式 */
.image-info-inputs {
  margin-top: 1.5rem;
  padding: 1rem;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.input-group {
  margin-bottom: 1rem;
}

.input-group:last-child {
  margin-bottom: 0;
}

.input-group label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: 500;
  color: #333;
}

.input-group input {
  width: 100%;
  padding: 0.5rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
  box-sizing: border-box;
}

.input-group input:focus {
  outline: none;
  border-color: #003366;
  box-shadow: 0 0 0 2px rgba(0, 51, 102, 0.1);
}

.weight-input-group {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.weight-description {
  font-size: 0.8rem;
  color: #666;
}
</style>